package com.org.controller;

import com.org.pojo.Admin;
import com.org.common.Result;
import com.org.service.AdminService;
import com.org.utils.JwtUtil;
import com.org.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: AdminController
 * Package: com.org.controller
 * Description:
 *
 * @Author Origin
 * @Create 2024/2/3 19:00
 * @Version 1.0
 */

@RestController
@RequestMapping("/admin")
@CrossOrigin//支持跨域
public class AdminController {
    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> params){
        String username = params.get("username");
        String password = params.get("password");
        //根据用户名查询User
        Admin admin = adminService.findByUserName(username);
        //判断是否查询到
        if(admin == null){
            return Result.error("用户名错误");
        }
        //判断密码是否正确
        if(admin.getPassword().equals(password)){
            //登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", admin.getId());
            claims.put("username", admin.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        //登录失败
        return Result.error("密码错误");
    }

    @GetMapping("/adminInfo")
    public Result<Admin> adminInfo(){
        Map<String, Object> map = ThreadLocalUtil.get();    //claims
        String username = (String) map.get("username");
        Admin user = adminService.findByUserName(username);
        return Result.success(user);
    }

    @PostMapping("/updateAvatar")
    public Result updateAvavtar(@RequestBody Map<String, String> params){
        @URL
        String url = params.get("url");
        adminService.updateAvatar(url);
        return Result.success();
    }




}
